<?php
	 /*  error_reporting(E_ALL);
          ini_set("display_errors", 1); */
		  
/* #############################################################################################
   @Modulo TASKI
   # Autor: 
   # e-mail: 
   # web : 
   ##################### copyright www.goldenfoxi.com - 2012 - ################################## */ 
if (!defined('_PS_VERSION_'))exit;
class PhonePayment extends PaymentModule
{
	private $Code_Html = '';
	
	private $_postErrors = array();
	
	public  $telefono_pp;
	public  $movil_pp;
	public $horario_pp;
	public $direccion_pp;
	public $comentario_pp;
	
	public function __construct()
	 {
		$this->name = 'phonepayment';
		$this->tab = 'payments_gateways';
		$this->currencies = true;
		$this->currencies_mode = 'checkbox';

	$config = Configuration::getMultiple(array( 'TELEFONO_PP', 'MOVIL_PP', 'HORARIO_PP', 'DIRECCION_PP', 'COMENTARIO_PP' ));
		
		if (isset($config['TELEFONO_PP']))$this->telefono_pp = $config['TELEFONO_PP'];
		
		if (isset($config['MOVIL_PP']))$this->movil_pp = $config['MOVIL_PP'];
		
		if (isset($config['HORARIO_PP']))$this->horario_pp = $config['HORARIO_PP'];
		
		if (isset($config['DIRECCION_PP']))$this->direccion_pp = $config['DIRECCION_PP'];
		
		if (isset($config['COMENTARIO_PP']))$this->comentario_pp = $config['COMENTARIO_PP'];

  parent::__construct();
	$this->displayName = $this->l('FORMA DE PAGO TASKI');
	$this->confirmUninstall = $this->l('Realmente desea desintalar el modulo Pago Telefonico?');
		
		if (!isset($this->telefono_pp) OR !isset($this->horario_pp) OR !isset($this->comentario_pp))
		$this->warning = $this->l('Este Modulo necesita parametros de configuracion para su correcto funcionamiento!');
		
		if (!sizeof(Currency::checkPaymentCurrencies($this->id)))
		$this->warning = $this->l('No hay una moneda relacionada para este modulo!');
		
         $this->extra_mail_vars = array('{telefono_pp}' => Configuration::get('TELEFONO_PP'),
		                                '{horario_pp}' => Configuration::get('HORARIO_PP'),
								        '{comentario_pp}' => Configuration::get('COMENTARIO_PP'));
     }

public function install(){
 		 if (!(Configuration::get('PS_OS_PHONEPAYMENT')))
		    {
             $this->AutoEstadoOrden();
             $this->MoverEmails();
			}
		if (!parent::install() 
		OR !$this->registerHook('payment') 
		OR !$this->registerHook('paymentReturn'))
			return false; return true;
	}

public function uninstall(){
			if (!Configuration::deleteByName('TELEFONO_PP')
				OR !Configuration::deleteByName('HORARIO_PP')
				OR !Configuration::deleteByName('COMENTARIO_PP')
				OR !Configuration::deleteByName('MOVIL_PP')
				OR !Configuration::deleteByName('DIRECCION_PP')
				OR !parent::uninstall())
			return false; return true;
	}
   
private function forzar_escritura($dire_carp, $lect){
        is_dir(dirname($dire_carp)) || forzar_escritura(dirname($dire_carp), $lect);
         return is_dir($dire_carp) || @mkdir($dire_carp, $lect);
    }
	

		  
private function AutoEstadoOrden()
   {
       $PhonePaymet = new OrderState();
        $languages = Language::getLanguages(false);
       foreach ($languages as $lang) {
             $PhonePaymet->name[(int) $lang['id_lang']] = $this->l('PAGO PENDIENTE');
             $PhonePaymet->template[(int) $lang['id_lang']] = $this->name;
        }
        $PhonePaymet->invoice = 0;
        $PhonePaymet->send_email = 1;
		$PhonePaymet->module_name = $this->name;
        $PhonePaymet->color = '#00CCCC';
        $PhonePaymet->unremovable = 1;
        $PhonePaymet->hidden = 0;
        $PhonePaymet->logable = 0;
        $PhonePaymet->delivery = 0;
		$PhonePaymet->shipped = 0;
		$PhonePaymet->paid = 0;
		$PhonePaymet->deleted = 0;
        $PhonePaymet->save();
$this->smartCopy((dirname(__file__) ."/img/icono_pp.gif"), (dirname(dirname(dirname(__file__))). "/img/os/$PhonePaymet->id.gif"));
    Configuration::updateValue("PS_OS_PHONEPAYMENT", $PhonePaymet->id);

		return true;
	}
	
public function smartCopy($source, $dest, $options = array('folderPermission'=>0755,'filePermission'=>0755)){
        $result = false;
        if (is_file($source)) 
		   {
          if ($dest[strlen($dest)-1]=='/') 
		     {
            if (!file_exists($dest)) 
			   {
       cmfcDirectory::makeAll($dest,$options['folderPermission'],true); 
	       }
             $__dest=$dest."/".basename($source);
               
			   } 
			   else {
                       $__dest=$dest;
                                     
				     }
          $result = copy($source, $__dest);
                   chmod($__dest,$options['filePermission']);
                  } 
				  elseif(is_dir($source)) 
				         {
                    if ($dest[strlen($dest)-1]=='/') 
					     {
                         if ($source[strlen($source)-1]=='/') 
						   {
                       } 
					   else {
                              $dest=$dest.basename($source);
                                       @mkdir($dest);
                                        chmod($dest,$options['filePermission']);
                         }
						 
                 } 
				 else {
          if ($source[strlen($source)-1]=='/') 
		  {
              @mkdir($dest,$options['folderPermission']);
                chmod($dest,$options['filePermission']);
                      } 
					  else {
                              @mkdir($dest, $options['folderPermission']);
                                 chmod($dest, $options['filePermission']);
                }
            }
                $dirHandle = opendir($source);
                    while($file=readdir($dirHandle)){
                     if($file!="." && $file!="..")
                        {
                           if(!is_dir($source."/".$file)) {
                                  $__dest = $dest."/".$file;
                    } 
					else {
                        $__dest=$dest."/".$file;
                    }
                    $result = smartCopy($source."/".$file, $__dest, $options);
                }
            }
            closedir($dirHandle);
        } 
		else {
            $result=false;
        }
        return $result;
    }
	
private function MoverEmails()
   {
   $languages = Db::getInstance()->ExecuteS('SELECT `iso_code` FROM `'._DB_PREFIX_.'lang` ');
      $mailTxtPath  = dirname(__file__) . '/emails/'.$this->name.'.txt';
      $mailHtmlPath = dirname(__file__) . '/emails/'.$this->name.'.html';
         foreach($languages as $lang)
		 {
           $mailDest = dirname( dirname (dirname(__file__) ) ) . '/mails/'.$lang['iso_code'].'/';
                      $this->forzar_escritura($mailDest, 0777);
                      $this->smartCopy($mailTxtPath, $mailDest);
                      $this->smartCopy($mailHtmlPath, $mailDest);
        }
        return true;
    }
		
private function _postValidation(){
		if (Tools::isSubmit('Config_boton')){
		
			if (!Tools::getValue('telefono_pp'))
			$this->_postErrors[] = $this->l('Ingrese un numero telefonico');
			
			if (!Tools::getValue('horario_pp'))
			$this->_postErrors[] = $this->l('Ingrese un horario de atencion al cliente por ejemplo: Argentina 09hs a 18hs');
			
			
			if 
			(!Tools::getValue('comentario_pp'))
			$this->_postErrors[] = $this->l('Debe adicionar un mensaje para su cliente. Esta informacion ayudara a su cliente a realizar el pago.');
			
			
			if (!Validate::isMessage(Tools::getValue('comentario_pp')))
			  $this->_postErrors[] = $this->l('La informacion de cliente posee caracteres no permitidos.');
			  
			if (!Validate::isPhoneNumber(Tools::getValue('telefono_pp')))
			  $this->_postErrors[] = $this->l('El numero telefonico es invalido, un numero valido seria: (011)54-23423-3333');
			  
		
			if (!Validate::isMessage(Tools::getValue('horario_pp')))
			  $this->_postErrors[] = $this->l('La informacion de cliente posee caracteres no permitidos.');
			  
		//opcionales
		 if(Tools::getValue('movil_pp')){
			  
		 if (!Validate::isPhoneNumber(Tools::getValue('movil_pp')))
			  $this->_postErrors[] = $this->l('El numero telefonico Movil es invalido.');
			  }	
		 if(Tools::getValue('direccion_pp')){
			  
		 if (!Validate::isAddress(Tools::getValue('direccion_pp')))
			  $this->_postErrors[] = $this->l('La direccion ingresada es invalida.');
			  }	
		  }
	}

public function _JS_PP_() {
		//global $currentIndex;
		echo '<script type="text/javascript">	
				var visible_actual = false;
				function visualiza(id){
				if(visible_actual == id)
				{ 
				visible_actual = false;document.getElementById(id).style.display = \'none\'
				}
				else {
				if(visible_actual)
				{ 
				document.getElementById(visible_actual).style.display = \'none\'}visible_actual = id;
				document.getElementById(visible_actual).style.display = \'block\'
				} 
				  }
			   </script>';
	 }
	 
private function _postProcess()
	{
		if (Tools::isSubmit('Config_boton'))
		{
			
			Configuration::updateValue('TELEFONO_PP', Tools::getValue('telefono_pp'));
			
			Configuration::updateValue('HORARIO_PP', Tools::getValue('horario_pp'));
			
			Configuration::updateValue('COMENTARIO_PP', Tools::getValue('comentario_pp'));

Tools::getValue('movil_pp') ? Configuration::updateValue('MOVIL_PP', Tools::getValue('movil_pp')) : Configuration::updateValue('MOVIL_PP', '');

Tools::getValue('direccion_pp') ? Configuration::updateValue('DIRECCION_PP', Tools::getValue('direccion_pp')) : Configuration::updateValue('DIRECCION_PP', '');
 	
		}
		
		$this->Code_Html .= '
		<div style="float:right;margin-right:245px;" class="conf confirm">
		'.$this->l('Configuracion almacenada correctamente.').'
		</div>
		';
	}

private function headerPhonepayment()
	{
	    $this->_JS_PP_();
		$this->Code_Html .= '

		<img alt="'.$this->name.'" border="0" src="'.$this->_path.'/images/'.$this->name.'.gif" style="float:left; margin-right:15px;margin-top:-5px">

<br />';
	}

	private function Form_PhonePayment()
	{
		$this->Code_Html .=
		'<form action="'.Tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset>
			<legend><img alt="-" src="'.$this->_path.'/images/database_gear.gif" />
			'.$this->l('Configuracion ').'
			</legend>
<p><h3>( * )'.$this->l('Informacion Obligatoria').'</h3></p>
			

<p>
<label for="telefono_pp">( * ) '.$this->l('Numero Telefonico:').'</label>
	<input type="text" name="telefono_pp" id="telefono" value="'.htmlentities(Tools::getValue('telefono_pp', $this->telefono_pp), ENT_COMPAT, 'UTF-8').'" style="width: 300px;" />
</p>	
<p>
<label for="horario_pp">( * ) '.$this->l('Horario de atencion:').'</label>
	<input type="text" name="horario_pp" id="telefono" value="'.htmlentities(Tools::getValue('horario_pp', $this->horario_pp), ENT_COMPAT, 'UTF-8').'" style="width: 300px;" />
	</p>

<p>
<label for="comentario_pp">( * ) '.$this->l('Informacion Para el cliente:').'</label>
<textarea name="comentario_pp" id="comentario_pp" rows="4" cols="53">'.htmlentities(Tools::getValue('comentario_pp', $this->comentario_pp), ENT_COMPAT, 'UTF-8').'</textarea>
</p>		


<p><h3>'.$this->l('Informacion Opcional').'</h3></p>

<p>
<label for="movil_pp">'.$this->l('Numero telefono celular:').'</label>

<input type="text" id="movil_pp" name="movil_pp" value="'.htmlentities(Tools::getValue('movil_pp', $this->movil_pp), ENT_COMPAT, 'UTF-8').'" />

</p>


<p>
<label for="direccion_pp">'.$this->l('Direccion Taski:').'</label>

<textarea name="direccion_pp" rows="4" cols="53">'.htmlentities(Tools::getValue('direccion_pp', $this->direccion_pp), ENT_COMPAT, 'UTF-8').'</textarea>
</p>



				<center>
<input style="cursor:pointer" class="button" name="Config_boton" value="'.$this->l('Guardar').'" type="submit" />
				</center>
			</fieldset>
		</form>';
	}

public function getContent()
	{
		$this->Code_Html = '
		<h2 style="float:right; margin-right:415px;">'.$this->displayName.'&nbsp;'.$this->version .'</h2>';
	if (Tools::isSubmit('Config_boton'))
		{
			$this->_postValidation();
	if (!sizeof($this->_postErrors))$this->_postProcess();
	else
		foreach ($this->_postErrors AS $err)$this->Code_Html .= '
		<div style="float:right;margin-right:245px;" class="alert error">
		'.'&nbsp;'.$this->l('ERROR:').'&nbsp;'.$err .'</div>';
		}
	else
			$this->Code_Html .= '<br />';
		$this->headerPhonepayment(); $this->Form_PhonePayment();

	return $this->Code_Html;
	}
public function checkCurrency($cart)
	{
		$currency_order = new Currency((int)($cart->id_currency));
		$currencies_module = $this->getCurrency((int)$cart->id_currency);
		$currency_default = Configuration::get('PS_CURRENCY_DEFAULT');
		
		if (is_array($currencies_module))
			foreach ($currencies_module as $currency_module)
				if ($currency_order->id == $currency_module['id_currency'])
					return true;
		return false;
	}

public function hookPayment($params)
	{
		if (!$this->active) return;
		if (!$this->checkCurrency($params['cart'])) return;
		$this->smarty->assign(array(
			'this_path' => $this->_path,
			'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->name.'/'
		));
		return $this->display(__FILE__, 'payment.tpl');
	}
	
public function hookPaymentReturn($params)
	{
		if (!$this->active) return;
		$state = $params['objOrder']->getCurrentState();
	
	if ($state == Configuration::get('PS_OS_PHONEPAYMENT') || $state == Configuration::get('PS_OS_OUTOFSTOCK'))
		{
			$this->smarty->assign(array(
				'total_to_pay' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false),
				'telefono_c' => trim(Configuration::get('TELEFONO_PP')),
				'horario_c' => trim(Configuration::get('HORARIO_PP')),
				'comentario_c' => Configuration::get('COMENTARIO_PP'),
				'movil_c' => trim(Configuration::get('MOVIL_PP')),
				'direccion_c' => trim(Configuration::get('DIRECCION_PP')),
				'this_path'  => $this->_path,
				'status'           => 'x_oka',
				'id_order'         => $params['objOrder']->id
			));
			if (isset($params['objOrder']->reference) && !empty($params['objOrder']->reference))
				$this->smarty->assign('reference', $params['objOrder']->reference);
		}
		else
			$this->smarty->assign('status', 'x_error');
		return $this->display(__FILE__, 'payment_return.tpl');
	}		
}
?>
